package com.shop.cereshop.app.dl.logic.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import com.shop.cereshop.app.redis.service.api.StringRedisService;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;


public class GetAccessToken {

    final static String url = "https://api-mop.chinaums.com/v1/token/access";

    public static String getToken(String appid, String appkey, StringRedisService redis) {
        if (redis.get("YLAccessToken") == null) {
            Date date = new Date();
            DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");

            String timestamp = format.format(date);
            String nonce = UUID.randomUUID().toString();

            Body b = new Body();
            b.appId = appid;
            b.timestamp = timestamp;
            b.nonce = nonce;
            b.signMethod = "SHA256";
            b.signature = getSignature(appid, timestamp, nonce, appkey);

            String response = request(url, b.toString());
            JSONObject json_test = JSONObject.fromObject(response);
            String t = String.valueOf(json_test.get("accessToken"));
            Integer time = (Integer) json_test.get("expiresIn");
            time *= 1000;
            redis.set("YLAccessToken", t, time);
            return t;
        } else {
            return String.valueOf(redis.get("YLAccessToken"));
        }
    }

    static String getSignature(String appId, String timestamp, String nonce, String appKey) {
        String sign = DigestUtils.sha256Hex(appId + timestamp + nonce + appKey);
        return sign;
    }

    static String request(String url, String reqBody) {
        String response = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
            httpUrlConnection.setRequestProperty("Content-Type", "application/json");
            httpUrlConnection.setDoOutput(true);
            httpUrlConnection.setDoInput(true);
            out = new PrintWriter(httpUrlConnection.getOutputStream());
            out.write(reqBody);
            out.flush();
            httpUrlConnection.connect();
            in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                response += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return response;
    }

    static class Body {

        String appId;

        String timestamp;

        String nonce;

        String signMethod;

        String signature;

        String toJson() {
            StringBuilder sb = new StringBuilder();
            sb.append("{");
            if (this.appId != null) sb.append("\"appId\":\"" + this.appId + "\",");
            if (this.timestamp != null) sb.append("\"timestamp\":\"" + this.timestamp + "\",");
            if (this.nonce != null) sb.append("\"nonce\":\"" + this.nonce + "\",");
            if (this.signMethod != null) sb.append("\"signMethod\":\"" + this.signMethod + "\",");
            if (this.signature != null) sb.append("\"signature\":\"" + this.signature + "\",");
            if (sb.charAt(sb.length() - 1) == ',')
                sb.deleteCharAt(sb.length() - 1);
            sb.append("}");
            return sb.toString();
        }

        public String toString() {
            return this.toJson();
        }


    }

}

